package com.cjy.service.Impl;

import com.cjy.dao.ImageTypeRepository;
import com.cjy.handler.NotFoundException;
import com.cjy.pojo.ImageType;
import com.cjy.service.ImageTypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ImageTypeServiceImpl implements ImageTypeService {

    @Autowired
    private ImageTypeRepository imageTypeRepository;

    @Override
    @Transactional
    public ImageType saveImageType(ImageType imageType) {
        ImageType save = null;
        try {
            save = imageTypeRepository.save(imageType);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("圖片类型保存失敗");
        }
        return save;
    }

    @Override
    public ImageType getImageType(Long id) {
        return imageTypeRepository.getOne(id);
    }

    @Override
    public ImageType getImageTypeByName(String name) {
        return imageTypeRepository.getImageTypeByName(name);
    }

    @Override
    public Page<ImageType> listImageType(Pageable pageable) {
        return imageTypeRepository.findAll(pageable);
    }

    @Override
    public List<ImageType> listImageType() {
        return imageTypeRepository.findAll();
    }

    @Override
    public List<ImageType> listImageTypeTop(Integer size) {
        Sort orders = Sort.by(Sort.Direction.DESC, "fasdfsFiles.size");
        Pageable pageable = PageRequest.of(0, size, orders);
        return imageTypeRepository.findTop(pageable);
    }

    @Override
    public ImageType updateImageType(Long id, ImageType imageType) {
        ImageType one = imageTypeRepository.getOne(id);
        if (one == null) {
            throw  new NotFoundException("图片类型不存在");
        }
        BeanUtils.copyProperties(imageType,one);
        return imageTypeRepository.save(one);
    }

    @Override
    public void deleteImageType(Long id) {
        imageTypeRepository.deleteById(id);
    }
}
